package com.lyeducation.sfcityexpressutil;

import com.lyeducation.util.MD5Util;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SFCityExpressUtil {
    @Autowired
    private SFCityExpressConfig sfCityExpressConfig;

    public void callApi(String api, String postBodyJson) throws java.io.UnsupportedEncodingException {
        String signature = sign(postBodyJson);
        StringBuffer sb = new StringBuffer();
        String url =
                sb.append(api).append("?sign=").append(signature).toString();
//        String url = api + "?sign=" + signature;
//        post(url, postBodyJson.getBytes("utf-8"));
    }

    public String sign(String content) throws java.io.UnsupportedEncodingException {
        // 假设原始内容JSON为 {"hello":"kitty"}
        // content : "{\"hello\":\"kitty\"}"
        StringBuffer sb = new StringBuffer();
        String signString =
                sb.append(content).append("&").append(sfCityExpressConfig.getDevId()).append("&").append(sfCityExpressConfig.getDevKey()).toString();

        // toSign : "{\"hello\":\"kitty\"}&1234567890&0123456789abcdef0123456789abcdef";
        System.out.println(signString);
        String md5Result = MD5Util.encodeMD5(signString);
        // md5Result : "ef3435b1480e553480e19e3e162fb0be"
        System.out.println(md5Result);
        String signResult = Base64.encode(md5Result.getBytes("utf-8"));
        // signResult : "ZWYzNDM1YjE0ODBlNTUzNDgwZTE5ZTNlMTYyZmIwYmU="

        return signResult;
    }

}
